<template>
  <view class="address-edit-container">
    <!-- 头部标题 -->
    <view class="input-section">
          <textarea 
            class="source-textarea"
            placeholder="请粘贴包含收件人信息的文本..."
            v-model="sourceText"
            @input="parseInfo"
            @paste="handlePaste"
            auto-height
          ></textarea>
        </view>
    <!-- 表单区域 -->
    <view class="form-container">
      <view class="form-item">
        <text class="label">收货人</text>
        <input 
          v-model="formData.name" 
          placeholder="请输入收货人姓名" 
        />
      </view>
      
      <view class="form-item">
        <text class="label">联系电话</text>
        <input 
          v-model="formData.mobile" 
          placeholder="请输入联系电话" 
          type="number"
        />
      </view>
      
      <view class="form-item" @click="showRegionPicker">
        <text class="label">所在地区</text>
        <input 
          v-model="regionText" 
          placeholder="请选择省市区" 
          disabled
        />
      </view>
      
      <view class="form-item">
        <text class="label">详细地址</text>
        <textarea 
          v-model="formData.address" 
          placeholder="请输入详细地址" 
        />
      </view>
      
      <view class="form-item switch-item">
        <text class="label">设为默认地址</text>
        <switch 
          :checked="isDefaultBoolean" 
          @change="onDefaultChange"
        />
      </view>
    </view>
    
    <!-- 底部按钮 -->
    <view class="footer">
      <!-- 编辑模式下显示保存按钮 -->
      <button 
        class="save-btn" 
        @click="saveAddress"
      >保存地址</button>
    </view>
    
    <!-- 地区选择器 -->
    <region-picker 
      ref="regionPicker" 
      @confirm="onRegionConfirm"
    />
  </view>
</template>
<script>
import RegionPicker from '@/components/region-picker/region-picker.vue'
  import {
	  	request
	  } from '@/utils/request.js'
export default {
  components: {
    RegionPicker
  },
  data() {
    return {
		id:'',
		showShibie:true,
		sourceText:'',
		 parsedInfo: {
		        name: '',
		        mobile: '',
		        regionText: '',  // 完整地区文本
		        province: '',    // 省份
		        city: '',        // 城市
		        area: '',        // 区/县
		        address: ''      // 详细地址
		      },
			     showToast: false,
			        // 省份数据用于地址识别
			      provinces: [
			              // 直辖市
			              { full: '北京市', short: '北京', type: '直辖市' },
			              { full: '上海市', short: '上海', type: '直辖市' },
			              { full: '天津市', short: '天津', type: '直辖市' },
			              { full: '重庆市', short: '重庆', type: '直辖市' },
			              // 省份
			              { full: '河北省', short: '河北', type: '省' },
			              { full: '山西省', short: '山西', type: '省' },
			              { full: '辽宁省', short: '辽宁', type: '省' },
			              { full: '吉林省', short: '吉林', type: '省' },
			              { full: '黑龙江省', short: '黑龙江', type: '省' },
			              { full: '江苏省', short: '江苏', type: '省' },
			              { full: '浙江省', short: '浙江', type: '省' },
			              { full: '安徽省', short: '安徽', type: '省' },
			              { full: '福建省', short: '福建', type: '省' },
			              { full: '江西省', short: '江西', type: '省' },
			              { full: '山东省', short: '山东', type: '省' },
			              { full: '河南省', short: '河南', type: '省' },
			              { full: '湖北省', short: '湖北', type: '省' },
			              { full: '湖南省', short: '湖南', type: '省' },
			              { full: '广东省', short: '广东', type: '省' },
			              { full: '海南省', short: '海南', type: '省' },
			              { full: '四川省', short: '四川', type: '省' },
			              { full: '贵州省', short: '贵州', type: '省' },
			              { full: '云南省', short: '云南', type: '省' },
			              { full: '陕西省', short: '陕西', type: '省' },
			              { full: '甘肃省', short: '甘肃', type: '省' },
			              { full: '青海省', short: '青海', type: '省' },
			              { full: '台湾省', short: '台湾', type: '省' },
			              // 自治区
			              { full: '内蒙古自治区', short: '内蒙古', type: '自治区' },
			              { full: '广西壮族自治区', short: '广西', type: '自治区' },
			              { full: '宁夏回族自治区', short: '宁夏', type: '自治区' },
			              { full: '新疆维吾尔自治区', short: '新疆', type: '自治区' },
			              { full: '西藏自治区', short: '西藏', type: '自治区' },
			              // 特别行政区
			              { full: '香港特别行政区', short: '香港', type: '特别行政区' },
			              { full: '澳门特别行政区', short: '澳门', type: '特别行政区' }
			            ],
			      
      addressId: null, // 地址ID
      formData: {
        name: '',
        mobile: '',
        province: '',
        city: '',
        area: '',
        address: '',
        is_default: false
      },
      tempRegion: [] // 临时存储选择的地区
    }
  },
  computed: {
	  hasResult() {
	        return this.sourceText.trim() !== '';
	      },
    // 计算地区显示文本
    regionText() {
      const { province, city, area } = this.formData
	  console.log(this.formData)
      return province && city && area ? `${province} ${city} ${area}` : ''
    },
	isDefaultBoolean() {
	     return this.formData.is_default === 1; // 1 → true, 0 → false
	   },
  },
  onLoad(options) {
    // 获取地址ID
    this.addressId = options.id || null
    
     
    // 加载地址数据
    if (options.id) {
		// this.showShibie = false
      // this.loadAddressData(options.id)
    }
	console.log(3333,options)
	if(options.dataJson){
		this.formData = { ...JSON.parse(options.dataJson) }
		console.log(222222,)
	}
  },
 
  methods: {
	  onDefaultChange(e) {
	        // 将布尔值转回 0/1
	        this.formData.is_default = e.detail.value ? 1 : 0;
			console.log(e.detail.value,this.formData.is_default)
	      },
    // 加载地址数据
    loadAddressData(id) {
      uni.showLoading({ title: '加载中...' })
      // 模拟API请求
      setTimeout(() => {
        // 模拟数据
        const mockData = {
          id: 1,
          name: '张三',
          mobile: '13800138000',
          province: '广东省',
          city: '深圳市',
          area: '南山区',
          address: '科技园路100号',
          is_default: true
        }
        
        this.formData = { ...mockData }
        uni.hideLoading()
      }, 500)
    },
    
    // 显示地区选择器
    showRegionPicker() {
	  console.log(this.$refs.regionPicker)
      this.$refs.regionPicker.isShow()
    },
    
    // 地区选择确认
    onRegionConfirm(region) {
      this.tempRegion = region
      this.formData.province = region[0]
      this.formData.city = region[1]
      this.formData.area = region[2]
    },
    
  
    // 进入编辑模式
    // enterEditMode() {
    //   this.isEditMode = true
    // },
    
    // 保存地址
    saveAddress() {
		let that = this;
      // 表单验证
      if (!this.validateForm()) return
      
      uni.showLoading({ title: '保存中...' })
      
     
     // 模拟API请求
     setTimeout(() => {
      
     		let params=that.formData;
			console.log(params)
			// params.is_default =  that.is_default?1:0
     		request({
     			url: 'address/info-save',
     			method: 'post',
     			data: params
     		}).then(res => {
     			if (res.status == 200) {
     				uni.hideLoading()
     				uni.showToast({ title: '保存成功' })
     				console.log(res.data)
     				// uni.navigateBack()
					// 返回上一页并刷新数据
					const pages = getCurrentPages()
					if (pages.length > 1) {
					  const prevPage = pages[pages.length - 2]
					  if (prevPage.$vm && prevPage.$vm.loadAddressList) {
					    prevPage.$vm.loadAddressList()
					  }
					}
					
					setTimeout(() => {
					  uni.navigateBack()
					}, 1500)
     			}
     		})
     		return
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }, 800)
    },
    
    // 表单验证
    validateForm() {
      const { name, mobile, province, city, area, address } = this.formData
      
      if (!name) {
        uni.showToast({ title: '请输入收货人姓名', icon: 'none' })
        return false
      }
      
      if (!/^1[3-9]\d{9}$/.test(mobile)) {
        uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
        return false
      }
      
      if (!province || !city || !area) {
        uni.showToast({ title: '请选择所在地区', icon: 'none' })
        return false
      }
      
      if (!address) {
        uni.showToast({ title: '请输入详细地址', icon: 'none' })
        return false
      }
      
      return true
    },
    
    // 删除地址
    deleteAddress() {
      uni.showModal({
        title: '提示',
        content: '确定要删除该地址吗？',
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({ title: '删除中...' })
            // 模拟API请求
            setTimeout(() => {
              uni.hideLoading()
              uni.showToast({ title: '删除成功' })
              
              // 返回上一页并刷新数据
              const pages = getCurrentPages()
              if (pages.length > 1) {
                const prevPage = pages[pages.length - 2]
                if (prevPage.$vm && prevPage.$vm.loadAddressList) {
                  prevPage.$vm.loadAddressList()
                }
              }
              
              setTimeout(() => {
                uni.navigateBack()
              }, 1500)
            }, 800)
          }
        }
      })
    }
 
   // 处理粘贴事件
     ,handlePaste() {
       // 延迟执行，确保粘贴内容已更新
       setTimeout(() => {
         this.parseInfo();
       }, 100);
     },
     
     // 解析信息
           // 解析信息
             parseInfo() {
               // 初始化解析结果
               const result = {
                 name: '',
                 mobile: '',
                 regionText: '',
                 province: '',
                 city: '',
                 area: '',
                 address: ''
               };
               
               if (!this.sourceText.trim()) {
                 this.parsedInfo = result;
                 return;
               }
               
               let text = this.sourceText.trim();
               
               // 1. 提取手机号
               const mobileRegex = /1[3-9]\d{9}/g;
               const mobileMatch = text.match(mobileRegex);
               if (mobileMatch && mobileMatch.length > 0) {
                 result.mobile = mobileMatch[0];
                 text = text.replace(mobileMatch[0], '').trim();
               }
               
               // 2. 提取姓名
               const nameMatch = text.match(/^[\u4e00-\u9fa5]{2,4}/);
               if (nameMatch) {
                 result.name = nameMatch[0];
                 text = text.replace(nameMatch[0], '').trim();
               }
               
               // 3. 提取地区信息（省市区）
               let remainingText = text;
               
               // 识别省份
               let matchedProvince = null;
               // 优先匹配全称
               for (let province of this.provinces) {
                 if (remainingText.includes(province.full)) {
                   matchedProvince = province;
                   remainingText = remainingText.replace(province.full, '').trim();
                   break;
                 }
               }
               
               // 匹配简称
               if (!matchedProvince) {
                 for (let province of this.provinces) {
                   if (remainingText.includes(province.short)) {
                     matchedProvince = province;
                     remainingText = remainingText.replace(province.short, '').trim();
                     break;
                   }
                 }
               }
               
               // 设置省份信息
               if (matchedProvince) {
                 if (matchedProvince.type === '省') {
                   result.province = `${matchedProvince.short}省`;
                 } else {
                   result.province = matchedProvince.short;
                 }
               }
               
               // 识别城市
               const cityRegex = /([^省市县区]*?[市]{1})/;
               const cityMatch = remainingText.match(cityRegex);
               if (cityMatch && cityMatch.length > 0) {
                 result.city = cityMatch[0];
                 remainingText = remainingText.replace(cityMatch[0], '').trim();
               }
               
               // 识别区域（区/县）
               const areaRegex = /([^省市县区]*?[区县]{1})/;
               const areaMatch = remainingText.match(areaRegex);
               if (areaMatch && areaMatch.length > 0) {
                 result.area = areaMatch[0];
                 remainingText = remainingText.replace(areaMatch[0], '').trim();
               }
               
               // 组合完整地区文本
               // result.regionText = [result.province, result.city, result.area].filter(Boolean).join('');
               
               // 详细地址
               result.address = remainingText.trim();
               
               // 更新解析结果
               this.parsedInfo = result;
			   this.formData = {
				   province:result.province, 
				   city:result.city,
					area:result.area,
					address:result.address,
					mobile:result.mobile,
					name:result.name,
			   }
			   
             },
    
    
 
  }
}
</script>

<style>
	.source-textarea {
	  width: 100%;
	  min-height: 150px;
	  padding: 12px;
	  background-color: #fff;
	  border: 1px solid #eee;
	  border-radius: 8px;
	  font-size: 14px;
	  line-height: 1.6;
	  box-sizing: border-box;
	}
.address-edit-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.header {
  padding: 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.header .title {
  font-size: 36rpx;
  font-weight: bold;
}

.form-container {
  margin-top: 20rpx;
  background-color: #fff;
  padding: 0 30rpx;
}

.form-item {
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
  position: relative;
  display: flex;
  align-items: center;
}

.form-item:last-child {
  border-bottom: none;
}

.label {
  width: 180rpx;
  font-size: 28rpx;
  color: #333;
}

input, textarea {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

textarea {
  height: 120rpx;
  padding: 10rpx 0;
}

.arrow {
  width: 40rpx;
  height: 40rpx;
  margin-left: 20rpx;
}

.switch-item {
  justify-content: space-between;
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
}

.save-btn, .edit-btn, .delete-btn {
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 30rpx;
}

.save-btn, .edit-btn {
  flex: 1;
  background-color: #e74c3c;
  color: #fff;
}

.delete-btn {
  flex: 1;
  margin-left: 20rpx;
  background-color: #fff;
  color: #e74c3c;
  border: 1rpx solid #e74c3c;
}
</style>
